<?php
/**
 * @user: thanatos <thanatos915@163.com>
 */

namespace common\models;

use Yii;
use yii\base\Model;
use yii\db\Exception;

class ReceiveForm extends Model
{
    public $identity;
    public $name;
    public $code;
    public $mobile;
    public $security;

    public function rules()
    {
        return [
            [['security', 'identity', 'mobile', 'name'], 'required'],
            [['security', 'identity', 'mobile', 'name', 'code'], 'string'],
        ];
    }

    public function submit($params)
    {
        $this->load($params, '');
        if (!$this->validate()) {
            return false;
        }
        // 验证验证码
        $sms = Yii::$app->sms;
        if (!$sms->validateCode($this->mobile, $this->code)) {
            $this->addError('security', '验证码不正确');
            return false;
        }

        $codeModel = Code::findOne(['security_sn' => $this->security, 'identity_code' => $this->identity]);
        if (empty($codeModel)) {
            $this->addError('security', '防伪码或身份码不正确');
            return false;
        }

        if ($codeModel->status !== 10) {
            $this->addError('security', '该红包已经领取过，不能重复领取');
            return false;
        }

        $transaction = Yii::$app->db->beginTransaction();
        try {
            $model = new Receive();
            $model->name = $this->name;
            $model->mobile = $this->mobile;
            $model->security_sn = $codeModel->security_sn;
            $model->identity_code = $codeModel->identity_code;
            $model->money = $codeModel->price;
            if (!$model->save()) {
                throw new Exception('防伪码或身份码不正确');
            }
            // 修改码状态
            $codeModel->status = 20;
            if (!$codeModel->save()) {
                file_put_contents('1.txt', json_encode($codeModel->getErrors()));
                throw new Exception('服务器错误，领取失败，请重试');
            }
            // TODO添加发送红包流程
            $app = Yii::$app->wechat->payment;
            $user = Yii::$app->session->get('wechat_user');
//            $user['id'] = 'ocSDQw2z0rVuo63i0surb7XpST7Y';
            if (empty($user)) {
                throw new Exception('微信授权失败，请刷新重试');
            }
            $result = $app->transfer->toBalance([
                'partner_trade_no' => time(),
                'openid' => $user['id'],
                'check_name' => 'NO_CHECK',
                'amount' => $codeModel->price * 100,
                'desc' => '红包返利'
            ]);
            if ($result['return_code'] !== 'SUCCESS') {
                throw new Exception('红包发送失败， 请联系管理员');
            }

            $transaction->commit();
        } catch (\Exception $e) {
            $this->addError('security', $e->getMessage());
            $transaction->rollBack();
            return false;
        }


        return true;

    }

}